import logging
from src.pages.base_page import BasePage
from src.common.assertion import assertion


class DynamicPage(BasePage):
    """
    动态页面
    """

    __text_area = ('xpath', '//textarea')
    __username = ('xpath', '//span[@class="feed_uname font14"]')
    __dynamic_content = ('xpath', '//a[class="feed_text"]')
    __like = ('xpath', '//span[@class="digg"]')
    __comment = ('xpath', '//span[@class="comment J-comment-show"]')
    __scan = ('xpath', '//span[@class="view"]')
    __option = ('xpath', '//span[@class="options"]')
    __view_dtl = ('xpath', '//a[@class="date"]')
    __comment_box = ('xpath', '//textarea[@class="comment_editor ev-comment-editor"]')
    __comment_btn = ('xpath', '//a[contains(text(), " 评 论 ")]')

    def create_dynamic(self, content):
        """
        发布动态
        Args:
            content: 动态内容
        """
        # 输入发布的动态内容
        self.send_keys(*self.__text_area, content)
        # 点击分享按钮
        self.click_btn('分享', tag='a')
        # 判断是否发布成功
        assertion(self.toast, '发布成功')
        self.page_refresh()

    def remove_dynamic(self):
        """
        删除动态
        """
        # 点击动态列表选项
        self.click(*self.__option)
        # 删除动态并确定
        self.click_btn('删除')
        self.click_btn('确定', tag='a')

    def add_comment(self, username, content):
        """
        为用户添加评论
        Args:
            username: 动态列表中的用户名
            content: 评论的内容
        """
        # 遍历动态列表中的所有的用户名，找到指定用户名在列表中的索引位置
        for i in range(len(self.get_elements(*self.__username))):
            if self.get_elements(*self.__username)[i].text == username:
                # 点击评论按钮
                self.get_elements(*self.__comment)[i].click()
                # 输入评论内容并提交
                self.get_elements(*self.__comment_box)[i].send_keys(content)
                self.get_elements(*self.__comment_btn)[i].click()
                break
            else:
                continue
        else:
            logging.error('当前页面没有用户：{}'.format(username))
